<?php


namespace Wonfu\HttpClient;


use Monolog\Logger;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Contracts\HttpClient\ResponseInterface;

class Client
{
    /**
     * @var CurlHttpClient
     */
    private $client;

    /**
     * @var AfterHandlerInterface
     */
    private $afterHandler;


    public function __construct()
    {
        $this->client = new CurlHttpClient();
    }

    /**
     * @param Logger $logger
     */
    public function setLogger(Logger $logger)
    {
        $this->client->setLogger($logger);
    }

    /**
     * @param AfterHandlerInterface $afterHandler
     */
    public function setAfterHandler(AfterHandlerInterface $afterHandler): void
    {
        $this->afterHandler = $afterHandler;
    }


    /**
     * @param string $method GET|POST
     * @param string $url
     * @param array $options
     * @return string
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function request(string $method, string $url, array $options = [])
    {

        $response = $this->client->request($method, $url, $options);
        if ($this->afterHandler && $this->afterHandler instanceof AfterHandlerInterface) {
            $this->afterHandler->hook(['method' => $method, 'url' => $url, 'options' => $options], $response);
        }

        return $response->getContent();
    }


}